<template>
  <view class="mp-html-wrapper">
    <!-- 如果内容为空，显示提示 -->
    <view v-if="!processedContent && contentSegments.length === 0" class="empty-content">
      <text>暂无内容</text>
    </view>
    
    <!-- 如果内容过长，分段显示 -->
    <view v-else-if="contentSegments.length > 1" class="segmented-content">
      <view 
        v-for="(segment, index) in contentSegments" 
        :key="index"
        class="content-segment"
      >
        <mp-html 
          :content="segment" 
          :tag-style="tagStyle"
          @load="onSegmentLoad(index)"
          @error="onSegmentError(index, $event)"
        />
      </view>
    </view>
    
    <!-- 正常显示 -->
    <mp-html 
      v-else-if="!usePlainText"
      :content="processedContent" 
      :tag-style="tagStyle"
      @load="onLoad"
      @error="onError"
    />
    
    <!-- 纯文本备用显示 -->
    <view v-else class="plain-text-content">
      <text>{{ plainTextContent }}</text>
    </view>
  </view>
</template>

<script setup>
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html.vue'
import { ref, computed } from 'vue'

const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  tagStyle: {
    type: Object,
    default: () => ({
      h1: 'font-size:36rpx;font-weight:bold;color:#333;margin:24rpx 0 16rpx 0;',
      h2: 'font-size:32rpx;font-weight:bold;color:#333;margin:20rpx 0 12rpx 0;',
      p: 'font-size:28rpx;color:#666;line-height:1.6;margin-bottom:16rpx;',
      span: 'font-weight:600;'
    })
  },
  maxLength: {
    type: Number,
    default: 10000 // 降低默认长度
  }
})

const emit = defineEmits(['load', 'error'])

// 分段内容
const contentSegments = ref([])
const segmentErrors = ref(new Set())
const usePlainText = ref(false)
const errorCount = ref(0)

// 纯文本内容
const plainTextContent = computed(() => {
  if (!props.content) return ''
  return props.content.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim()
})

// 处理复杂的 HTML 内容
const processedContent = computed(() => {
  if (!props.content) return ''
  
  try {
    let processed = props.content
    
    // 1. 移除所有内联样式
    processed = processed.replace(/style="[^"]*"/g, '')
    
    // 2. 移除不兼容的标签和属性
    processed = processed.replace(/<script[^>]*>.*?<\/script>/gi, '')
    processed = processed.replace(/<style[^>]*>.*?<\/style>/gi, '')
    processed = processed.replace(/<iframe[^>]*>.*?<\/iframe>/gi, '')
    processed = processed.replace(/<link[^>]*>/gi, '')
    processed = processed.replace(/<meta[^>]*>/gi, '')
    
    // 3. 简化标签，移除所有属性
    processed = processed.replace(/<(\w+)[^>]*>/g, '<$1>')
    
    // 4. 移除不支持的标签
    processed = processed.replace(/<(?:table|tr|td|th|thead|tbody|colgroup|col)[^>]*>/gi, '')
    processed = processed.replace(/<\/(?:table|tr|td|th|thead|tbody|colgroup|col)>/gi, '')
    
    // 5. 移除空标签
    processed = processed.replace(/<(\w+)>\s*<\/\1>/g, '')
    
    // 6. 清理多余的空格和换行
    processed = processed.replace(/\s+/g, ' ').trim()
    
    // 7. 如果内容仍然过长，进行分段
    if (processed.length > props.maxLength) {
      segmentContent(processed)
      return ''
    }
    
    return processed
  } catch (error) {
    console.error('HTML 处理失败:', error)
    // 如果处理失败，切换到纯文本模式
    usePlainText.value = true
    return ''
  }
})

// 分段处理长内容
const segmentContent = (content) => {
  const segments = []
  const maxSegmentLength = props.maxLength / 2
  
  // 按标题分割
  const parts = content.split(/<h[1-6][^>]*>/)
  
  let currentSegment = ''
  
  for (let i = 0; i < parts.length; i++) {
    const part = parts[i]
    if (part.trim()) {
      // 找到对应的标题标签
      const titleMatch = content.match(/<h[1-6][^>]*>/)
      const titleTag = titleMatch ? titleMatch[0].replace(/<(\w+)[^>]*>/, '<$1>') : ''
      
      const wrappedPart = titleTag + part
      
      if (currentSegment.length + wrappedPart.length > maxSegmentLength) {
        if (currentSegment) {
          segments.push(currentSegment)
        }
        currentSegment = wrappedPart
      } else {
        currentSegment += wrappedPart
      }
    }
  }
  
  if (currentSegment) {
    segments.push(currentSegment)
  }
  
  // 如果没有按标题分割成功，按段落分割
  if (segments.length <= 1) {
    const paragraphs = content.split(/<\/?p[^>]*>/)
    let currentSegment = ''
    
    for (const paragraph of paragraphs) {
      if (paragraph.trim()) {
        const wrappedParagraph = `<p>${paragraph}</p>`
        
        if (currentSegment.length + wrappedParagraph.length > maxSegmentLength) {
          if (currentSegment) {
            segments.push(currentSegment)
          }
          currentSegment = wrappedParagraph
        } else {
          currentSegment += wrappedParagraph
        }
      }
    }
    
    if (currentSegment) {
      segments.push(currentSegment)
    }
  }
  
  contentSegments.value = segments
}

const onLoad = () => {
  console.log('mp-html 加载成功')
  errorCount.value = 0
  emit('load')
}

const onError = (error) => {
  console.error('mp-html 渲染错误:', error)
  errorCount.value++
  
  // 如果错误次数过多，切换到纯文本模式
  if (errorCount.value >= 3) {
    usePlainText.value = true
    console.log('切换到纯文本模式')
  }
  
  emit('error', error)
}

const onSegmentLoad = (index) => {
  console.log(`分段 ${index} 加载成功`)
}

const onSegmentError = (index, error) => {
  console.error(`分段 ${index} 渲染错误:`, error)
  segmentErrors.value.add(index)
  
  // 如果所有分段都出错，切换到纯文本模式
  if (segmentErrors.value.size === contentSegments.value.length) {
    usePlainText.value = true
    console.log('所有分段渲染失败，切换到纯文本模式')
    emit('error', new Error('所有内容分段渲染失败'))
  }
}
</script>

<style lang="scss" scoped>
.mp-html-wrapper {
  padding: 24rpx;
  background: #fff;
}

.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200rpx;
  color: #999;
  font-size: 28rpx;
}

.segmented-content {
  .content-segment {
    margin-bottom: 32rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.plain-text-content {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  
  text {
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style>